package com.linkstec.http;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

//import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.apache.http.nio.reactor.ConnectingIOReactor;
import org.apache.http.nio.reactor.IOReactorException;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;

public class WechatHttpClient {
	//基础支持: 获取access_token接口 /token
	//https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx23a3dd5be3312cde&secret=c32a98183ebb39e9fd8b119d36bfab76
    public static void main(String[] args){
    	//设置代理IP、端口、协议（请分别替换）
//        HttpHost proxy = new HttpHost("172.16.0.1", 3128, "http");

        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(50000)
                .setSocketTimeout(50000)
                .setConnectionRequestTimeout(1000)
//                .setProxy(proxy)
                .build();

        //配置io线程
        IOReactorConfig ioReactorConfig = IOReactorConfig.custom().
                setIoThreadCount(Runtime.getRuntime().availableProcessors())
                .setSoKeepAlive(true)
                .build();
        //设置连接池大小
        ConnectingIOReactor ioReactor=null;
        try {
            ioReactor = new DefaultConnectingIOReactor(ioReactorConfig);
        } catch (IOReactorException e) {
            e.printStackTrace();
        }
        PoolingNHttpClientConnectionManager connManager = new PoolingNHttpClientConnectionManager(ioReactor);
        connManager.setMaxTotal(100);
        connManager.setDefaultMaxPerRoute(100);


        final CloseableHttpAsyncClient client = HttpAsyncClients.custom().
                setConnectionManager(connManager)
                .setDefaultRequestConfig(requestConfig)
                .build();


        //构造请求
        //https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN
        String access_token = "22_NGEgT2gE7VKY_DJcT53R8p2MqCM5hOZ3R-ONFeBev79aO34yqzM_YU--S2eyYMapR8y-y590GVJXngEx1vC3UQtq7CtclKxayn3qXswA9tOV09pjHOCkNXeHJnXswSAwgMOt17ojSZeM561MVLSjABAJZG";
        String urlPost = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+access_token;
//        String urlPost = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=22_p6wdl0qC7yoXWembbz0EivxbMrxGBVi-3BJkET1NyLqIO0DTttaxXCz8rr95V38f907zmpv4pR7Cgg2RIk59j7_1StrVC3e43yiFKWZrPtvXgLFmXjCmzRIvsWRyOWauDK5mHAt0MPbIdJJtVQBdAHALGR";
        HttpPost httpPost = new HttpPost(urlPost);
//        httpPost.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
//        httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
        httpPost.setHeader("Content-Type", "application/json;encoding=utf-8");
        StringEntity entity = null;
        try {
        	HashMap<String, Object> postMap = new HashMap<String, Object>();
//        	postMap.put("touser", "ooD9m51vdBheJwtzDUZntfChVyzQ");
//        	postMap.put("touser", "ooD9m526deYDP2qAfe5ex6ec5TVU");
        	postMap.put("touser", "ooD9m5xIglSlMEFKPAThmUK2XgRs");
//        	postMap.put("template_id", "D6NxyvbgcAhAFFRxVvzN0zD0oshfIm5QXV30tLMMfAs");
//        	postMap.put("template_id", "_unqYW7B07PM112l0lSewlCU2V3lFsnMRDE8yRNjIBs");
        	postMap.put("template_id", "gEjWlN3Pd1N8am7vRSSGSygAgJc7vzYpfQSNTm71-_I");
//        	postMap.put("url", "http://weixin.qq.com/download");
        	postMap.put("url", "http://www.baidu.com");
        	postMap.put("topcolor", "#FF0000");
        	HashMap<String, Object> data = new HashMap<String, Object>();
        	HashMap<String, String> data1 = new HashMap<String, String>();
        	data1.put("value", "您有新的订单，请注意查收");
        	data1.put("color", "#173177");
        	data.put("first", data1);
        	HashMap<String, String> data2 = new HashMap<String, String>();
        	data2.put("value", "20190612111");
        	data2.put("color", "#173177");
        	data.put("orderid", data2);
        	HashMap<String, String> data3 = new HashMap<String, String>();
        	data3.put("value", "1000万");
        	data3.put("color", "#173177");
        	data.put("amount", data3);
        	HashMap<String, String> data4 = new HashMap<String, String>();
        	data4.put("value", "你真是个美女\n\n地址：天涯海角");
        	data4.put("color", "#F7BA0B");
        	data.put("remark", data4);
        	postMap.put("data", data);
        	
            String a = new String(JSON.toJSONString(postMap));
            System.out.println(a);
//            entity = new StringEntity(a);//中文乱码
            entity = new StringEntity(a,"UTF-8");
            entity.setContentType("application/json; charset=utf-8"); 
        } catch (Exception e) {
            e.printStackTrace();
        }
        doPost(client, httpPost, entity);
        
        //构造请求
        /*String geturl = "https://www.baidu.com";
        HttpGet httpGet = new HttpGet(geturl);
        long start = System.currentTimeMillis();
        for (int i = 0;i<1;i++) {
        	doGet(client, httpGet);
        }
        System.out.println(" cost is:"+(System.currentTimeMillis()-start));*/
        
        while(true){
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
public static void doPost(CloseableHttpAsyncClient client, HttpPost httpPost, StringEntity entity) {
	
    httpPost.setEntity(entity);

    //start
    client.start();

    //异步请求
    client.execute(httpPost, new Back());
	
}
public static void doGet(CloseableHttpAsyncClient client, HttpGet httpGet) {
	//start
	client.start();
	
	//异步请求
	client.execute(httpGet, new Back());
	
}
    static class Back implements FutureCallback<HttpResponse>{

        private long start = System.currentTimeMillis();
        Back(){
        }

        public void completed(HttpResponse httpResponse) {
            try {
                System.out.println("cost is:"+(System.currentTimeMillis()-start)+":"+EntityUtils.toString(httpResponse.getEntity()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public void failed(Exception e) {
            System.err.println("错误 cost is:"+(System.currentTimeMillis()-start)+":"+e);
        }

        public void cancelled() {

        }
    }
}